﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MSACommerce.AuthenticationCenter.Utility;
using MSACommerce.AuthenticationCenter.Utility.RSA;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace MSACommerce.AuthenticationCenter.Controllers
{
    /// <summary>
    /// 专门用来颁发token的
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        #region MyRegion

        private ILogger<AuthenticationController> _logger = null;
        private IJWTService _iJWTService = null;
        private readonly IConfiguration _iConfiguration;

        public AuthenticationController(ILoggerFactory factory,
            ILogger<AuthenticationController> logger,
            IConfiguration configuration
            , IJWTService service)
        {
            this._logger = logger;
            this._iConfiguration = configuration;
            this._iJWTService = service;
        }

        #endregion MyRegion

        [Route("Get")]
        [HttpGet]
        public IEnumerable<int> Get()
        {
            return new List<int>() { 1, 2, 3, 4, 6, 7 };
        }

        [Route("GetKey")]
        [HttpGet]
        public string GetKey()
        {
            string keyDir = Directory.GetCurrentDirectory();
            if (RSAHelper.TryGetKeyParameters(keyDir, false, out RSAParameters keyParams) == false)
            {
                keyParams = RSAHelper.GenerateAndSaveKey(keyDir, false);
            }

            return JsonConvert.SerializeObject(keyParams);
        }

        [Route("Login")]
        [HttpPost]
        public string Login(string name, string password)
        {
            CurrentUserModel currentUser = new CurrentUserModel()
            {
                Id = 123,
                Account = name,
                EMail = "",
                Mobile = "",
                Sex = 1,
                Age = 33,
                Name = name,
                Role = "test"
            };

            string token = this._iJWTService.GetToken(currentUser);
            return JsonConvert.SerializeObject(new
            {
                result = true,
                token = token,
                msg = ""
            });
        }
    }
}